package com.itheima.ums.controller;

import cn.hutool.core.collection.CollUtil;
import com.itheima.mall.pojo.Resource;
import com.itheima.mall.vo.PageResult;
import com.itheima.ums.service.UmsResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/resource")
public class UmsResourceController {

    @Autowired
    private UmsResourceService umsResourceService;

    /**
     * 添加后台资源
     *
     * @param resource
     * @return
     */
    @PostMapping("/create")
    public ResponseEntity create(@RequestBody Resource resource) {
        Integer count = umsResourceService.create(resource);
        if (count <= 0) {
            return ResponseEntity.ok("ok");
        }
        return ResponseEntity.ok(count);
    }

    /**
     * 根据ID删除后台资源
     *
     * @param id
     * @return
     */
    @PostMapping("/delete/{id}")
    public ResponseEntity deleteById(@PathVariable("id") Long id) {
        Integer count = umsResourceService.deleteById(id);
        return ResponseEntity.ok(count);
    }

    /**
     * 分页模糊查询后台资源
     *
     * @param pageNum
     * @param pageSize
     * @param nameKeyword
     * @param urlKeyword
     * @param categoryId
     * @return
     */
    @GetMapping("/list")
    public ResponseEntity list(@RequestParam(defaultValue = "1") Integer pageNum,
                               @RequestParam(defaultValue = "10") Integer pageSize,
                               String nameKeyword, String urlKeyword, Long categoryId) {
        PageResult pageResult = umsResourceService.list(pageNum, pageSize, nameKeyword, urlKeyword, categoryId);
        if (pageResult == null) {
            return ResponseEntity.ok("ok");
        }
        return ResponseEntity.ok(pageResult);

    }

    /**
     * 查询所有后台资源
     *
     * @return
     */
    @GetMapping("/listAll")
    public ResponseEntity listAll() {
        List<Resource> list = umsResourceService.listAll();
        if (CollUtil.isEmpty(list)) {
            return ResponseEntity.ok("ok");
        }
        return ResponseEntity.ok(list);

    }

    /**
     * 修改后台资源
     *
     * @param id
     * @return
     */
    @PostMapping("/update/{id}")
    public ResponseEntity updateById(@PathVariable("id") Long id, @RequestBody Resource resource) {
        Integer count = umsResourceService.updateById(id, resource);
        if (count <= 0) {
            return ResponseEntity.ok("ok");
        }
        return ResponseEntity.ok(count);
    }

    /**
     * 根据ID获取资源详情
     *
     * @param id
     * @return
     */
    @GetMapping("{id}")
    public ResponseEntity getById(@PathVariable("id") Long id) {
        Resource resource = umsResourceService.getById(id);
        if (resource == null) {
            return ResponseEntity.ok("ok");
        }

        return ResponseEntity.ok(resource);
    }
}
